package com.yk.i_wms.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yk.i_wms.common.model.PageResult;
import com.yk.i_wms.common.model.Result;
import com.yk.i_wms.dto.SmsReceiveDocDTO;
import com.yk.i_wms.model.SmsReceiveDoc;
import com.yk.i_wms.model.SmsReceiveDocDetail;
import com.yk.i_wms.model.UmsItem;
import com.yk.i_wms.service.ISmsReceiveDocDetailService;
import com.yk.i_wms.service.ISmsReceiveDocService;
import com.yk.i_wms.service.IUmsItemService;
import com.yk.i_wms.util.EasyPoiExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 入库单
 *
 * @author hbq
 * @date 2021-04-01 17:36:42
 */
@Slf4j
@CrossOrigin
@RestController
@Api(tags = "入库单")
@RequestMapping("sms")
public class SmsReceiveDocController {
    @Autowired
    private ISmsReceiveDocService smsReceiveDocService;
    @Autowired
    private ISmsReceiveDocDetailService smsReceiveDocDetailService;
    @Autowired
    private IUmsItemService umsItemService;
    /**
     * 扫码入库
     */
    @ApiOperation(value = "扫码入库")
    @PostMapping("/smsReceiveDoc/scanSN")
    public Result scanSN(@RequestBody Map<String, Object> map) {
        return smsReceiveDocService.scanSN(map);
    }

    /**
     * 根据单号查详情
     */
    @ApiOperation(value = "根据单号查详情")
    @PostMapping("/smsReceiveDoc/selAllByDocNo")
    public Result selAllByDocNo(@RequestBody Map<String, Object> params) {
        String docNo = MapUtil.getStr(params, "docNo");
        SmsReceiveDoc receiveDoc = smsReceiveDocService.getOne(new LambdaQueryWrapper<SmsReceiveDoc>()
                .eq(SmsReceiveDoc::getDocNo, docNo));
        Map<String, Object> resultMap = BeanUtil.beanToMap(receiveDoc);
        List<Map<String, Object>> received = new ArrayList<>();
        List<SmsReceiveDocDetail> receiveDocDetails = smsReceiveDocDetailService.list(new LambdaQueryWrapper<SmsReceiveDocDetail>().eq(SmsReceiveDocDetail::getDocNo, docNo));
        for (SmsReceiveDocDetail receiveDocDetail : receiveDocDetails) {
            Map<String, Object> map = BeanUtil.beanToMap(receiveDocDetail);
            String itemCode = receiveDocDetail.getItemCode();
            UmsItem item = umsItemService.getOne(new LambdaQueryWrapper<UmsItem>().eq(UmsItem::getItemCode, itemCode));
            Integer minPackNum=0;
            if (item != null&&item.getMinPackNum()!=null) {
                minPackNum=item.getMinPackNum();
            }
            map.put("itemMinPackNum",minPackNum);
            received.add(map);
        }
        resultMap.put("receiveDocDetails",received);
        return Result.succeed(resultMap, "查询成功");
    }
    /**
     * 列表
     */
    @ApiOperation(value = "查询列表")
    @PostMapping("/smsReceiveDoc/list")
    public Result<PageResult> list(@RequestBody Map<String, Object> params) {
        Page<Map> list= smsReceiveDocService.findList(params);
        return Result.succeed(PageResult.restPage(list),"查询成功");
    }

    /**
     * 查询
     */
    @ApiOperation(value = "查询")
    @PostMapping("/smsReceiveDoc/sel/{id}")
    public Result findUserById(@PathVariable Long id) {
        SmsReceiveDoc model = smsReceiveDocService.getById(id);
        return Result.succeed(model, "查询成功");
    }
    /**
     * 新增or更新(包含详情)
     */
    @ApiOperation(value = "新增or更新(包含详情)")
    @PostMapping("/smsReceiveDoc/saveAll")
    public Result saveAll(@RequestBody SmsReceiveDocDTO smsReceiveDocDTO) {
        return smsReceiveDocService.saveAll(smsReceiveDocDTO);
    }

    /**
     * 关结
     */
    @ApiOperation(value = "关结")
    @PostMapping("/smsReceiveDoc/close")
    public Result close(@RequestBody SmsReceiveDoc smsReceiveDoc) {
        return smsReceiveDocService.close(smsReceiveDoc);
    }

    /**
     * 新增or更新
     */
    @ApiOperation(value = "新增or更新")
    @PostMapping("/smsReceiveDoc/save")
    public Result save(@RequestBody SmsReceiveDoc smsReceiveDoc) {
        smsReceiveDocService.saveOrUpdate(smsReceiveDoc);
        return Result.succeed("保存成功");
    }

    /**
         * 批量新增or更新
         */
    @ApiOperation(value = "批量新增or更新")
    @PostMapping("/smsReceiveDoc/saveBatch")
    public Result saveBatch(@RequestBody Map<String,List<SmsReceiveDoc>> map) {
        List<SmsReceiveDoc> models = map.get("models");
        smsReceiveDocService.saveOrUpdateBatch(models);
        return Result.succeed("保存成功");
    }

    /**
     * 删除
     */
    @ApiOperation(value = "批量删除")
    @PostMapping("/smsReceiveDoc/del")
    public Result delete(@RequestBody Map<String,List<Long>> map) {
         return smsReceiveDocService.delete(map);
    }
    
    /**
     * 导入
     */
    @ApiOperation(value = "导入")
    @PostMapping("/smsReceiveDoc/leadIn")
    public  Result leadIn(MultipartFile excel) throws Exception {
        int rowNum = 0;
        if (!excel.isEmpty()) {
            List<SmsReceiveDoc> list = EasyPoiExcelUtil.importExcel(excel, 1, 1, SmsReceiveDoc.class);
            rowNum = list.size();
            if (rowNum > 0) {
                list.forEach(u -> {
                        smsReceiveDocService.save(u);
                });
                return Result.succeed("成功导入信息"+rowNum+"行数据");
            }
        }
        return Result.failed("导入失败");
    }
    
    /**
     * 导出（传入ids数组，选择指定id）
     */
    @ApiOperation(value = "导出（传入ids数组，选择指定id）")
    @PostMapping("/smsReceiveDoc/leadOut")
    public void leadOut(@RequestBody Map<String,List<Long>> map,HttpServletResponse response) throws IOException {
        List<Long> ids = map.get("ids");
        List<SmsReceiveDoc> smsReceiveDocList = ids==null||ids.isEmpty()? smsReceiveDocService.list(new QueryWrapper<>()):(List)smsReceiveDocService.listByIds(ids);
        //导出操作
        EasyPoiExcelUtil.exportExcel(smsReceiveDocList, "入库单导出", "入库单导出", SmsReceiveDoc.class, "smsReceiveDoc.xls", response);
    }
}
